#include "at24c64.h"
void at24c64_init(void)
{
	i2c_init();
}
int8_t at24c64_write(uint16_t addr, uint8_t data)
{
	int ret;
	i2c_start();
	i2c_send_byte(AT24C64_WRITE_ADDR);
	ret = i2c_recv_ack();
	if (ret == 1)
	{
		return -1;
	}
	i2c_send_byte(addr >> 8);
	i2c_recv_ack();
	i2c_send_byte(addr & 0xff);
	ret = i2c_recv_ack();
	if (ret == 1)
	{
		return -2;
	}
	i2c_send_byte(data);
	ret = i2c_recv_ack();
	if (ret == 1)
	{
		return -3;
	}
	i2c_stop();
	return AT24C64_OK;
}

int8_t at24c64_read(uint16_t addr, uint8_t *data)
{
	int ret;
	i2c_start();
	i2c_send_byte(AT24C64_WRITE_ADDR);
	ret = i2c_recv_ack();
	if (ret == 1)
	{
		return -1;
	}
	i2c_send_byte(addr >> 8);
	ret = i2c_recv_ack();
	if (ret == 1)
	{
		return -2;
	}
	i2c_send_byte(addr & 0xff);
	ret = i2c_recv_ack();
	if (ret == 1)
	{
		return -3;
	}
	i2c_start();
	i2c_send_byte(AT24C64_READ_ADDR);
	ret = i2c_recv_ack();
	if (ret == 1)
	{
		return -4;
	}
	*data = i2c_recv_byte();
	i2c_send_ack(1);
	i2c_stop();
	return AT24C64_OK;
}

#if 0
void at24_test(void)
{int main(void)
{
	float temperature;
	char data;
	int ret;
	Usart1_Init(115200);
	printf("STM32_EXP_V2_BOARD\r\n");

	AHT10_Init();

	at24c64_init();

//	ret = at24c64_write(0, 'A');
//	if(ret!=AT24C64_OK){
//		printf("write error\r\n");
//		goto err;
//	}
//	delay_ms(100);
//	ret= at24c64_read(0,&data);
//	if(ret!=AT24C64_OK){
//		printf("read error\r\n");
//		goto err;
//	}

	printf("data:%c\r\n", data);

	char op;

	while (1)
	{

		op = getchar();
		if (op == 't')
		{
			AHT10_Read();
			temperature = AHT10_GetTemperature();
			printf("temperature:%.2f\r\n", temperature);
		}
		else if (op == 'r')
		{
			at24c64_read(0, &data);
			printf("data:%c\r\n", data);
		}
		else{
			at24c64_write(0, op);
		}
		

		//delay_ms(1000);
	}
err:
	while(1){
	}
}}

#endif
